<?php

namespace app\admin\model;

use think\facade\Cache;
use think\Model;

class AdminMenuModel extends Model
{

    protected $table = '__ADMIN_MENU__';

    /**
     * 获取菜单树状关系
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMenuTree()
    {
        $all_menu = $this->order('order asc')->select()->toArray();
        return $tree = $this->getTree($all_menu);
    }

    public function getMenu($id)
    {
        $menu = $this->find($id);
        if (empty($menu)) {
            return '';
        } else {
            return $menu->toArray();
        }
    }

    //获取树状关系
    function getTree($array, $pid = 0, $level = 0)
    {
        static $list = [];
        foreach ($array as $key => $value) {
            if ($value['pid'] == $pid) {
                $value['level'] = $level;
                $list[] = $value;
                unset($array[$key]);
                $this->getTree($array, $value['id'], $level + 1);
            }
        }
        return $list;
    }

    public function menuAdd($post_data)
    {
        if ($this->allowField(true)->save($post_data)) {
            return ['status' => 'y', 'info' => '菜单添加成功'];
        } else {
            return ['status' => 'n', 'info' => '菜单添加失败'];
        }
    }

    public function menuEdit($post_data)
    {
        //不能把自己修改成自己的父类
        if ($post_data['id'] == $post_data['pid']) {
            return ['status' => 'n', 'info' => '自己不能是自己的父类哦'];
        }
        if (false !== $this->allowField(true)->save($post_data, ['id' => $post_data['id']])) {
            Cache::clear();
            return ['status' => 'y', 'info' => '菜单修改成功'];
        } else {
            return ['status' => 'n', 'info' => '菜单修改失败'];
        }
    }
}